package com.woniu.dashboard;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author 杨光 微信号:tolryg
 * @time 14:19
 */

@RestController
@ServerEndpoint("/dashboard")
public class DashboardController {


    @Autowired
    private DashboardService dashboardService;


    private static List<Session>  sessionList = new CopyOnWriteArrayList<>();

    //当收到消息的时候会调用这个方法
    @OnMessage
    public void onMessage(Session session, String message){
        System.out.println("收到消息"+message);
    }
    //当连接建立的时候，这个方法就会被调用
    @OnOpen
    public void onOpen(Session session){

        boolean flag = sessionList.add(session);
        System.out.println("flag = " + flag);
        System.out.println("session = " + session);
    }

    //当连接关闭的时候，这个方法就会被调用
    @OnClose
    public void onClose(Session session){
        sessionList.remove(session);
    }
    //当连接有异常的时候，这个方法就会被调用
    @OnError
    public void onError(Session session,Throwable throwable){
        throwable.printStackTrace();
    }



    @Scheduled(fixedRate = 5000)
    public void sendMessage() throws IOException {

        System.out.println("执行。。"+new Date());

        List<Dashboard> list = dashboardService.selectDashboardList(new Dashboard());

        ObjectMapper objectMapper = new ObjectMapper();
        String json =null;
        json = objectMapper.writeValueAsString(list);

        System.out.println("json = " + json);
        System.out.println("-------------------------------");

        System.out.println("sessionList = " + sessionList);

        for (Session session : sessionList) {
            session.getBasicRemote().sendText(json);
        }
    }


}
